package com.koala.dbUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MySqlAgent {
	
	
	Connection conexion;
	ResultSet res=null;
	
	String driver = "com.mysql.jdbc.Driver";
	
	String usuario;
	String pass;
	String url="jdbc:mysql://";
	String bd;
	
	
	public MySqlAgent(String url, String usuario, String pass, String bd) {
		
		this.url+=url+"/"+bd;
		this.usuario=usuario;
		this.pass=pass;
		this.bd=bd;
		
	}
	
	public void conectar(){
		try{
			
			Class.forName(driver);
			conexion = DriverManager.getConnection(url,usuario,pass);
			
			
		} catch (Exception ex){
			
			System.out.println(ex.toString());
			
		}
	}
	
	public void ejecutarSQL(String sql){
		
		try {
			
			PreparedStatement pstm = conexion.prepareStatement(sql);
			
			res = pstm.executeQuery();
			
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		
	}
	
public void ejecutarInsertSQL(String sql){
		
		try {
			
			PreparedStatement pstm = conexion.prepareStatement(sql);
			
			int res = pstm.executeUpdate(sql);
			
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		
	}
	
	public void CerrarConexion(){
			
		try {
		
			if(!conexion.isClosed())
				conexion.close();		
	
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	
	public ResultSet getRes() {
		return res;
	}

	protected void finalize() throws Throwable {
			
			try{			
				if(!conexion.isClosed())
					conexion.close();		
			}
			catch (Exception e) {

			}
		
		
		super.finalize();
	}

}
